﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.WebApp.Models.Ado;

namespace XSTDZ.ERP.WebApp.Controllers
{
    /// <summary>
    /// 工作组
    /// </summary>
    public class WorkGroupController : Controller
    {
        //
        // GET: /WorkGroup/
        private readonly IWorkGroupService workGroupServiceImpl = ServiceLocator.Instance.GetService<IWorkGroupService>();
        public ActionResult Index()
        {
            return View();
        }

        #region 工作组
        [NoAuthorizated("Add")]
        public ActionResult Add(Guid? id)
        {
            
            if (id.HasValue)
            {
                Guid wid = Guid.Empty;
                Guid.TryParse(id.Value.ToString(), out wid);
                var wg = workGroupServiceImpl.GetWorkGroup(wid);
                BindIsLeader(wg.IsHeadman.ToString());
                GetWorkGroupNames(wg.GroupName);
                return View(wg);
            }
            BindIsLeader("");
            GetWorkGroupNames("");
            return View();
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(WorkGroupDto workGroup)
        {
            #region 处理介面元素
            
            var model = new ProductCheckBillModel();
            var userId = model.GetRequestFormValues(this.HttpContext, "Name_val");
            if (!Guid.Empty.Equals(userId))
            {
                workGroup.UserID = userId;
                ModelState.Remove("UserID");
                ModelState.Remove("Name");
            }
            else
            {
                if (workGroup.Id.Equals(Guid.Empty))
                {
                    ModelState.AddModelError("Name", "组员姓名不能为空！");
                }
            }

            var isLD = this.HttpContext.Request.Form["IsHeadman"];
            if (!string.IsNullOrEmpty(isLD) && isLD == "1")
            {
                workGroup.IsHeadman = 1;
            }
            else
            {
                workGroup.IsHeadman = 0;
            }

          
            

            #endregion
            BindIsLeader(workGroup.IsHeadman.ToString());
            GetWorkGroupNames(workGroup.GroupName);
            if (ModelState.IsValid)
            {
               

                if (workGroup.Id == null || Guid.Empty.Equals(workGroup.Id))
                {
                    if (this.workGroupServiceImpl.IsExist(workGroup))
                    {
                        ModelState.AddModelError("UserID", "该组用户已存在！");
                        return View(workGroup);
                    }

                    this.workGroupServiceImpl.AddWorkGroup(workGroup);
                }
                else
                {
                    if (workGroup.IsHeadman != 0)
                    {
                        if (this.workGroupServiceImpl.IsExistWorkGroupHeadman(workGroup))
                        {
                            ModelState.AddModelError("IsHeadman", "已存在组长！");
                            return View(workGroup);
                        }
                    }

                    this.workGroupServiceImpl.UpdateWorkGroup(workGroup);
                }
               
                ViewBag.PostState = 9;
            }
           
            return View(workGroup);
        }

        public ActionResult Delete(Guid id)
        {
            try
            {
                workGroupServiceImpl.DeleteWorkGroup(id);
            }
            catch (Exception)
            {
                return Content("0");
            }
          
            return Content("9");
        }
        #endregion
        #region 获得工作组列表
        [NoAuthorizated("GetJsonOfWorkGroup")]
        public ActionResult GetJsonOfWorkGroup()
        {
            #region 暂不用EF
            //var workGroupService = workGroupServiceImpl.GetAllWorkGroup();
            //if (workGroupService != null && workGroupService.Count() != 0)
            //{
            //    var jsonResult = workGroupService.Select(u => { u.DeletedState = u.Deleted == 0 ? "正常" : "已删除"; u.Headman = u.IsHeadman == 0 ? "成员" : "组长"; return u; });
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"" + workGroupService.Count() + "\"}";

            //    return Content(target);
            //}
            //return View();
            #endregion
            return Content(new BLLQuery().GetWorkGoroups(this.HttpContext));
        }
        #endregion
        #region 是否组长
        private void BindIsLeader(string isLeader)
        {
            var list= new List<SelectListItem> { 
                 new SelectListItem{ Text="是", Value="1"},
                 new SelectListItem{ Text="否", Value="0", Selected=true}
            };
            if (!string.IsNullOrEmpty(isLeader))
            {
                list.ForEach(t => { if (t.Value.ToString() == isLeader) { t.Selected = true; } });
            }
            ViewBag.IsHeadman = list;
        }
        #endregion
        #region 码表获得工作组名称
        private void GetWorkGroupNames(string _groupCode)
          {
              var model = new RefeModel();
              var refeList = model.GetRefeByModuleName(RefeTypeOption.工作组名称);
              ViewBag.WorkGroupNames = model.GetDropDownListItemsByCode(refeList, _groupCode);
          }
        #endregion
    }
}
